package cn.csc.module.pay.job.reconciliation;

import cn.csc.framework.common.util.date.DateUtils;
import cn.csc.framework.jzb.core.JzbClient;
import cn.csc.framework.jzb.vo.JzbResponse;
import cn.csc.framework.tenant.core.job.TenantJob;
import cn.csc.module.pay.convert.jzbreconciliation.PayJzbReconciliationConvert;
import cn.csc.module.pay.dal.dataobject.jzbreconciliation.PayJzbReconciliationDO;
import cn.csc.module.pay.dal.mysql.jzbreconciliation.PayJzbReconciliationMapper;
import cn.hutool.core.io.FileUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.pingan.openbank.api.sdk.entity.FileRequest;
import com.sdb.util.Base64;
import com.sdb.util.SignUtil;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.File;
import java.util.Arrays;
import java.util.Calendar;
import java.util.List;
import java.util.Optional;

/**
 * 见证宝对账文件下载，平安要求每天下载一次
 *
 * @author liuchuang
 * @version 1.0
 * @date 2023/5/15 17:59
 * @modify
 */
@Component
@TenantJob // 多租户
@Slf4j
public class JzbReconciliation {

    // 昨天：DateUtils.date2Str(DateUtils.dateDayPlus(-1L),DateUtils.FORMAT_YEAR_MONTH_DAY_S);

    private final String ALG = "DesEde/CBC/PKCS5Padding";

    @Autowired
    private JzbClient jzbClient;

    @Autowired
    private PayJzbReconciliationMapper mapper;

    @Value("${csc.vol-path.file}")
    private String filePath;

    @Value("${csc.reconciliation.fileTypes}")
    private String fileTypes;

    /**
     * 下载对账文件信息，保存到数据库
     *
     * @return
     * @throws Exception
     */
    @XxlJob("reconciliationJob")
    public ReturnT<String> reconciliationJob() throws Exception {
        String dateStr = DateUtils.date2Str(DateUtils.dateDayPlus(-1L), DateUtils.FORMAT_YEAR_MONTH_DAY_S);
        // @TODO 建表循环处理
        log.info("reconciliationJob fileTypes={} , dateStr={}", fileTypes, dateStr);
        Arrays.asList(fileTypes.split(",")).forEach(type -> {
            JSONObject jsonObject = new JSONObject();

            //文件类型:充值文件-CZ 提现文件-TX 交易文件-JY 余额文件-YE 合约文件-HY 鉴权文件-JQ POS文件-POS 资金汇总账户明细文件-JG 平台归集账户明细文件-GJ
            jsonObject.put("FileType", type);
            //文件日期:文件日期不能超过查询交易当天日期
            jsonObject.put("FileDate", dateStr);

            //保留域
            jsonObject.put("ReservedMsg", "查询成功");
            JzbResponse response = jzbClient.send(jsonObject, "KFEJZB6103", "/V1.0/ReconciliationDocumentQuery");
            log.info("reconciliationJob: " + response.getData().toJSONString());

            if (response.isSuccess()) {
                ReconciliationDocumentQueryResp resp = JSON.parseObject(response.getData().get("Data").toString(), ReconciliationDocumentQueryResp.class);
                List<PayJzbReconciliationDO> list = PayJzbReconciliationConvert.INSTANCE.convertList(resp.getTranItemArray());
                list.forEach(item -> {
                    item.setFileType(type);
                    item.setFileDate(dateStr);
                    // TODO 补偿执行，处理唯一键冲突
                    mapper.insert(item);
                });
            }

        });

        return new ReturnT<>("下载对账文件信息，保存到数据库成功，对账文件日期"+dateStr);
    }

    /**
     * 下载对账文件
     *
     * @return
     * @throws Exception
     */
    @XxlJob("reconciliationDownloadJob")
    public ReturnT<String> reconciliationDownloadJob() throws Exception {
        String dateStr = DateUtils.date2Str(DateUtils.dateDayPlus(-1L), DateUtils.FORMAT_YEAR_MONTH_DAY_S);
        log.info("reconciliationDownloadJob filePath : {}, dateStr: {}", filePath, dateStr);

        Arrays.asList(fileTypes.split(",")).forEach(type -> {
            // 下载文件保存路径，docker部署时将其挂载出来
            String basePath = filePath + File.separator + type + File.separator + dateStr + File.separator;
            log.info("reconciliationDownloadJob basePath: {}", basePath);
            if (!FileUtil.isDirectory(basePath)) {
                FileUtil.mkdir(basePath);
            }
            List<PayJzbReconciliationDO> list = mapper.selectList(type, dateStr, null, null);
            log.info("reconciliationDownloadJob list: {}", list);
            list.stream().filter(item -> !item.getFileName().equals("none.txt")).forEach(item -> {
                log.info("reconciliationDownloadJob: "+item);
                try {
                    // 下载对账文件
                    FileRequest fileRequest = new FileRequest();
                    fileRequest.setFileNo(item.getDrawCode());
                    // 6103接口返回的FilName格式为CZ2023041530041.txt.enc
                    // FilePathName为文件下载存储路径（带文件名的绝对路径）
                    fileRequest.setFilePathName(basePath + item.getFileName());
                    jzbClient.getApiClient().fileDownLoad(fileRequest);

                    // 解密
                    String srcFile = basePath + item.getFileName();
                    String zipFile = basePath + item.getFileName().replace("enc", "zip");
                    String destFile = basePath + item.getFileName().replace(".enc", "");
                    byte[] bkey = Base64.decode(item.getRandomPassword().getBytes());
                    SignUtil.decrypt(srcFile, zipFile, bkey, ALG, "DesEde", null);
                    // 解压
                    SignUtil.uncompress(zipFile, destFile);

                    // 更新下载状态
                    item.setStatus(1);
                    mapper.updateById(item);

                } catch (Exception e) {
                    e.printStackTrace();
                }
            });

        });

        return new ReturnT<>(String.format("下载对账文件成功，对账文件类型[ %s ],对账文件日期[%s]", fileTypes, dateStr));
    }


}
